<?php

namespace App\Http\Controllers\Seller;

use App\Models\FreightTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class FreightController extends BaseController
{
    /**
     * FreightController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['sideMenu' => 'freight']);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        $items = $this->shop->freightTemplates;
        return $this->view('seller.freight.index', compact('items'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function newTemplate(Request $request)
    {
        $template_id = $request->input('template_id', 0);
        if ($template_id) {
            $template = $this->shop->freightTemplates()->find($template_id);
        } else {
            $template = new FreightTemplate();
        }

        return $this->view('seller.freight.newtemplate', compact('template_id', 'template'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function store(Request $request)
    {
        $template_id = $request->input('template_id', 0);
        $newtemplate = Arr::only($request->input('template', []), [
            'template_name',
            'valuation',
            'start_quantity',
            'start_fee',
            'growth_quantity',
            'growth_fee',
            'delivery_areas',
            'free_amount',
            'free_quantity'
        ]);

        if ($template_id) {
            $template = $this->shop->freightTemplates()->find($template_id);
            if ($template) {
                $template->update($newtemplate);
            }
        } else {
            $this->shop->freightTemplates()->create($newtemplate);
        }

        return $this->messager()->setRedirectTo('seller/freight')->render();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $template_id = $request->input('template_id', 0);
        $this->shop->freightTemplates()->where('template_id', $template_id)->delete();
        return ajaxReturn();
    }
}
